import React, { useState, useEffect } from 'react'
import {
  Card,
  Descriptions,
  Button,
  Space,
  Tag,
  Typography,
  Alert,
  Divider,
  message
} from 'antd'
import {
  getToken,
  parseTokenPayload,
  isTokenExpired,
  getCurrentUser,
  formatAuthHeader,
  isAuthenticated
} from '../utils/auth'

const { Text, Title } = Typography

interface TokenInfoProps {
  showRefreshButton?: boolean
  onRefresh?: () => void
}

const TokenInfo: React.FC<TokenInfoProps> = ({ 
  showRefreshButton = false, 
  onRefresh 
}) => {
  const [tokenData, setTokenData] = useState<any>(null)
  const [isExpired, setIsExpired] = useState(false)
  const [refreshTime, setRefreshTime] = useState(Date.now())

  // 刷新token信息
  const refreshTokenInfo = () => {
    const token = getToken()
    if (token) {
      const payload = parseTokenPayload(token)
      const expired = isTokenExpired(token)
      setTokenData(payload)
      setIsExpired(expired)
    } else {
      setTokenData(null)
      setIsExpired(false)
    }
    setRefreshTime(Date.now())
  }

  useEffect(() => {
    refreshTokenInfo()
    
    // 每30秒检查一次token状态
    const interval = setInterval(refreshTokenInfo, 30000)
    
    return () => clearInterval(interval)
  }, [])

  const token = getToken()
  const isLoggedIn = isAuthenticated()
  const currentUser = getCurrentUser()

  // 复制token到剪贴板
  const copyToken = () => {
    if (token) {
      navigator.clipboard.writeText(token)
      message.success('Token已复制到剪贴板')
    }
  }

  // 复制Authorization header
  const copyAuthHeader = () => {
    if (token) {
      const authHeader = formatAuthHeader(token)
      navigator.clipboard.writeText(authHeader)
      message.success('Authorization Header已复制到剪贴板')
    }
  }

  // 格式化时间戳
  const formatTimestamp = (timestamp: number) => {
    return new Date(timestamp * 1000).toLocaleString('zh-CN')
  }

  if (!isLoggedIn) {
    return (
      <Card title="Token 信息">
        <Alert
          message="未登录"
          description="当前用户未登录，无法获取token信息"
          type="warning"
          showIcon
        />
      </Card>
    )
  }

  return (
    <div>
      <Card 
        title="Token 信息" 
        extra={
          <Space>
            <Button size="small" onClick={refreshTokenInfo}>
              刷新
            </Button>
            {showRefreshButton && onRefresh && (
              <Button size="small" type="primary" onClick={onRefresh}>
                刷新Token
              </Button>
            )}
          </Space>
        }
      >
        {isExpired && (
          <Alert
            message="Token已过期"
            description="当前token已过期，请重新登录或刷新token"
            type="error"
            showIcon
            style={{ marginBottom: 16 }}
          />
        )}
        
        <Descriptions column={1} bordered size="small">
          <Descriptions.Item label="登录状态">
            <Tag color={isLoggedIn ? 'success' : 'error'}>
              {isLoggedIn ? '已登录' : '未登录'}
            </Tag>
          </Descriptions.Item>
          
          <Descriptions.Item label="Token状态">
            <Tag color={isExpired ? 'error' : 'success'}>
              {isExpired ? '已过期' : '有效'}
            </Tag>
          </Descriptions.Item>
          
          {tokenData && (
            <>
              <Descriptions.Item label="用户ID">
                {tokenData.userId || tokenData.sub || '未知'}
              </Descriptions.Item>
              
              <Descriptions.Item label="用户名">
                {tokenData.username || tokenData.name || '未知'}
              </Descriptions.Item>
              
              <Descriptions.Item label="角色">
                {tokenData.role || tokenData.roles?.join(', ') || '未知'}
              </Descriptions.Item>
              
              <Descriptions.Item label="签发时间">
                {tokenData.iat ? formatTimestamp(tokenData.iat) : '未知'}
              </Descriptions.Item>
              
              <Descriptions.Item label="过期时间">
                {tokenData.exp ? formatTimestamp(tokenData.exp) : '未知'}
              </Descriptions.Item>
              
              <Descriptions.Item label="签发者">
                {tokenData.iss || '未知'}
              </Descriptions.Item>
            </>
          )}
          
          <Descriptions.Item label="最后更新">
            {new Date(refreshTime).toLocaleString('zh-CN')}
          </Descriptions.Item>
        </Descriptions>
        
        <Divider />
        
        <div>
          <Title level={5}>Token 操作</Title>
          <Space wrap>
            <Button onClick={copyToken} disabled={!token}>
              复制Token
            </Button>
            <Button onClick={copyAuthHeader} disabled={!token}>
              复制Authorization Header
            </Button>
          </Space>
        </div>
        
        <Divider />
        
        <div>
          <Title level={5}>Token 内容预览</Title>
          <Text code style={{ fontSize: '12px', wordBreak: 'break-all' }}>
            {token ? `${token.substring(0, 50)}...` : '无token'}
          </Text>
        </div>
        
        {tokenData && (
          <>
            <Divider />
            <div>
              <Title level={5}>解析后的Payload</Title>
              <pre style={{ 
                background: '#f5f5f5', 
                padding: '12px', 
                borderRadius: '4px',
                fontSize: '12px',
                overflow: 'auto',
                maxHeight: '200px'
              }}>
                {JSON.stringify(tokenData, null, 2)}
              </pre>
            </div>
          </>
        )}
      </Card>
    </div>
  )
}

export default TokenInfo